<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use addons\epay\library\Service;
use think\Log;
use app\common\model\Pay;
use app\common\model\activity\Activity;
use app\common\model\activity\ActivityOrder;
use app\common\model\bb\Order as ModelBbOrder;
use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\goods\Spec;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order;
use app\common\model\order\Total;
use app\common\model\raise\Attached;
use app\common\model\raise\Order as RaiseOrder;
use app\common\model\User as ModelUser;
use think\Db;

/**
 * 微信支付接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    /**
     * 支付成功回调
     */
    //微信回调
    public  function notify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, config('site.apiv3_private_key'));
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            $order = ModelOrder::where('sn', $order_sn)->find();
                            if (!$order) {
                                return true;
                            }
                            ModelOrder::where('id', $order['id'])->update(['status' => 1, 'transaction_id' => $transaction_id, 'paytime' => time()]);
                            break;
                    }

                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
    //退款回调地址
    public static function refund_notify()
    {
        
        $notifiedData = file_get_contents('php://input');
        Log::write('验证退款：' . $notifiedData);
        $data = json_decode($notifiedData, true);
     
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, config('site.apiv3_private_key'));
            Log::write('退款成功：' . $orderData);
            $orderData = json_decode($orderData, true);
            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order_sn = $orderData['out_trade_no']; //商户订单号
                // 启动事务
                Db::startTrans();
                try {
                    $order = ModelOrder::where('sn', $order_sn)->find();
                    if (!$order) {
                        return true;
                    }
                    $res= ModelOrder::where('id', $order['id'])->update(['status' => '-1', 'refund_transaction_id' => $transaction_id, 'canceltime' => time()]);
                    if ($order['coupon_id'] && $res) {
                        Log::where('id', $order['coupon_id'])->update(['state' => 1]);
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
}
